package router

import (
	"bytes"
	"fmt"
	"gitee.com/baidugoogle/ccu/src/handler"
	"gitee.com/baidugoogle/ccu/src/ulog"
	"github.com/gin-gonic/gin"
	"golang.org/x/net/websocket"
	"io/ioutil"
	"log"
	"net/http"
)

func InitRouter(r *gin.Engine) *gin.Engine {
	InitRouterGeneral(r)

	var api = r.Group("/ccu/api/v1")
	api.Use(func(ctx *gin.Context) {
		data, err := ctx.GetRawData()
		if err != nil {
			log.Println(err.Error())
			return
		}

		ctx.Request.Body = ioutil.NopCloser(bytes.NewBuffer(data)) // 关键点
		ctx.Next()
	})

	var apiDevice = api.Group("/device")
	apiDevice.GET("/ws", ginWebsocketHandler(handler.RtcWebsocketConnHandle))

	return r
}

// websocket是否检查origin
var WebSocketCheckOrigin = false

func myCheckOrigin(config *websocket.Config, req *http.Request) (err error) {
	if WebSocketCheckOrigin == false {
		return nil
	}
	config.Origin, err = websocket.Origin(config, req)
	if err == nil && config.Origin == nil {
		return fmt.Errorf("null origin")
	}
	return err
}

// websocket.Handler 转 gin HandlerFunc
func ginWebsocketHandler(wsConnHandle websocket.Handler) gin.HandlerFunc {
	return func(c *gin.Context) {
		ulog.Info("new websocket conn %v, %v", c.Request.RemoteAddr, c.IsWebsocket())
		if c.IsWebsocket() {
			//wsConnHandle.ServeHTTP(c.Writer, c.Request)
			s := websocket.Server{Handler: wsConnHandle, Handshake: myCheckOrigin}
			s.ServeHTTP(c.Writer, c.Request)
		} else {
			ulog.Error("===not websocket request===")
			_, _ = c.Writer.WriteString("===not websocket request===")
		}
	}
}

func InitRouterGeneral(r *gin.Engine) {
	r.Use(Cors())
	r.StaticFS("/www", gin.Dir("./home/www", true))

	r.GET("/", func(c *gin.Context) {
		//c.Redirect(http.StatusMovedPermanently, "/home")
		data, _ := ioutil.ReadFile("./home/index.html")
		_, _ = c.Writer.Write(data)
	})
}

// Cors 跨域
func Cors() gin.HandlerFunc {
	return func(c *gin.Context) {
		method := c.Request.Method

		c.Header("Access-Control-Allow-Origin", "*")
		c.Header("Access-Control-Allow-Headers", "Content-Type,AccessToken,X-CSRF-Token, Authorization, Token")
		c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, PATCH, DELETE")
		c.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers, Content-Type")
		c.Header("Access-Control-Allow-Credentials", "true")

		//放行所有OPTIONS方法
		if method == "OPTIONS" {
			c.AbortWithStatus(http.StatusNoContent)
		}
		// 处理请求
		c.Next()
	}
}
